// 引入库
const path = require('path');
const sqlite3 = require('sqlite3');


let rootPath = path.join(__dirname, './tomato.db');
// 连接或创建数据库
let db = new sqlite3.Database(rootPath);

// 生成数据库表格
function initSQLite() {
    // db = new sqlite3.Database(rootPath);
    runSQL(`
        create table tomatoTable 
        (
            name text not null,
            creatTime text not null,
            duringTime int not null,
            startFlag boolean not null,
            bgSrc text not null,
            taskEndCount int not null,
            taskId text not null
        );
    `)
    // db.close();
}

// 执行sql语句
function runSQL(sqlstr) {
    db.serialize(()=>{
        db.run(sqlstr);
    })
}

// 查询番茄钟数据
function getTomatoData() {
    db = new sqlite3.Database(rootPath);
    return new Promise((reslove)=>{
        db.all('select * from tomatoTable', (err, data)=>{
            reslove(data);
        });
    })
}
// 向番茄钟表插入新数据
function insertNewInfo(d) {
    let insertInfo = db.prepare('insert into tomatoTable (name, creatTime, duringTime, startFlag, bgSrc, taskEndCount, taskId) values (?, ?, ?, ?, ?, ?, ?)')
    insertInfo.run(d.name, d.creatTime, d.duringTime, d.startFlag, d.bgSrc, d.taskEndCount, d.taskId );
    insertInfo.finalize();
}
// 从番茄钟表删除数据
function deleteNewInfo(taskId) {
    let del = db.prepare("delete from tomatoTable where taskId = ? "); 
    del.run(taskId); 
    del.finalize();
}
// 修改番茄钟任务完成次数
function updateTaskEndCount(arg) {
    let update = db.prepare('update tomatoTable set taskEndCount = ? where taskId = ?');
    update.run(arg.taskEndCount, arg.taskId);
    update.finalize();
}



module.exports = { initSQLite, getTomatoData, insertNewInfo, deleteNewInfo, updateTaskEndCount }